import React, { useMemo, useState, useRef } from 'react';
import { Menu, Dropdown, Button, Checkbox } from 'antd';
import { DownOutlined } from '@ant-design/icons';
import PropTypes from 'prop-types';
import { useClickAway } from 'ahooks';
import styles from './ColumnControlButton.less';

/**
 * @name 表格列控制按钮
 * @param { Array } columns 表格列配置 列配置中 canControl !== false 的列均可控制列显示隐藏
 * @param { Function } onChangeColumns 列隐藏、显示变化事件
 */
const ColumnControlButton = ({ key, columns = [], onChangeColumns = () => {} }) => {
  const ref = useRef();
  const [visible, setVisible] = useState(false);

  useClickAway(() => {
    setVisible(false);
  }, ref);

  const menu = useMemo(() => {
    const canControlColumns = columns.filter(t => t.canControl !== false);
    return (
      <Menu className={styles.menu}>
        {canControlColumns.map((item) => {
          const { dataIndex, title, hideInTable = false } = item;
          return (
            <Menu.Item key={dataIndex}>
              <Checkbox
                checked={!hideInTable}
                onClick={(e) => {
                  e.stopPropagation();
                  onChangeColumns(item, !hideInTable);
                  return false;
                }}
              >
                {title}
              </Checkbox>
            </Menu.Item>
          );
        })}
      </Menu>
    );
  }, [columns]);

  const openDropDown = () => {
    setVisible(!visible);
  };

  return (
    <div ref={ref}>
      <Dropdown
        key={key}
        visible={visible}
        overlay={menu}
        placement="bottomRight"
        trigger={['click']}
        getPopupContainer={(node) => {
          if (node) {
            return node.parentNode;
          }
          return document.body;
        }}
      >
        <Button type="primary" onClick={openDropDown}>
          更多
          <DownOutlined />
        </Button>
      </Dropdown>
    </div>
  );
};

ColumnControlButton.propTypes = {
  columns: PropTypes.array,
  onChangeColumns: PropTypes.func,
};

ColumnControlButton.defaultProps = {
  columns: [],
  onChangeColumns: () => {},
};
export default React.memo(ColumnControlButton);
